<?php
namespace app\index\model;
use think\Model;
class Jccount extends BaseModel{
    function readjc()
    {
        $res = $this->getLock();
        if ($res['id'] == '' || $res['times'] <= 0) {
            return "";
        }
        
        
        return $this->getJc();
    }
    function openjc()
    {
        $res = $this->getLock();
        if ($res['id'] == '' || $res['times'] <= 0) {
    
            return $this->saveLock();
        }
    }
    
    function kaijaing(){
        $res = $this->getLock();
        if ($res['id'] == '') {
            return "";
        }
        $jc = new Jc();
        $nowjc = $jc->checkALl($res['id']);
        if(!$nowjc||$nowjc['status']==1){
            return;
        }
        sleep($res['times']);
        $socket = new Socket();
        $socket->sendResult($nowjc['result'],$nowjc['name']);
        $this->saveJchis($nowjc);
        //检查他的上级，
        $this->checkStr2($nowjc['id'], $nowjc['result'],$nowjc['name']);
        //检查谁中奖了，推送给个人
        $this->checkStr($nowjc['id'], $nowjc['result'],$nowjc['name']);
    }
    /*获取当前
     * 到时间计算，开奖
     * 开奖前首先获取数据库是否已经后台设置开奖
     * 若无进行计算
     * 最近开奖结果存入文件jchis.php
     * 当前进行存入文件jclock.php
     * 推送进行通知，前端收到通知后显示
     * 通知包括最近开奖，以及中奖人，以及现在进行的
     *
     */
    
    function saveLock()
    {
        $file = "jclock.php";
        $fp = fopen($file, "w");
        if (flock($fp, LOCK_EX|LOCK_NB)) {
            $datas = null;
            $res = $this->getLock();
            $times = $res['times'];
            if ($times <= 0) {
                $jc = new Jc();
                $status = $jc->checkStatus($res['id']);
                if (!$status){
                    $this->kaijaing();
                    flock($fp, LOCK_UN); // 解锁
                    fclose($fp);
                    return ;
                }
                
                
                
                $datas = $jc->addJC($this->getSYSTime(),$res['name']);
                $this->setLock($datas);
            }
            flock($fp, LOCK_UN); // 解锁
            fclose($fp);
            if ($datas){
                $socket = new Socket();
                $socket->sendNew();
            }
        }
    }
    
    function finish_request(){
        ob_start();
        header("Connection: close\r\n");
        header('Content-Encoding: none\r\n');
        
        // your code here
        
        
        $size = ob_get_length();
        header("Content-Length: ". $size . "\r\n");
        ob_end_flush();
        flush();
    }
    
    
    function checkStr($qi_id,$str,$qiname=""){
        $first = intval(str_get_last($str, 3));
        $second = intval(str_get_last($str, 2));
        $last = intval(str_get_last($str, 1));
        $where["qi_id"]=$qi_id;
        $datas = [];
        $peilv = [];
        $jc = new Jc();
        $socket = new Socket();
        $typesss = new Types();
       $typesssRes = $typesss->getTypes2();
        if ($last==$second){
            array_push($peilv, $typesssRes[3]['peilv']);
            //合
            $where["xiazhu_type"]=["in","9"];
            $datas = $jc->getJCDetailsAll($qi_id, $where);
        }else {
            array_push($peilv, $typesssRes[1]['peilv']);
            array_push($peilv, $typesssRes[2]['peilv']);
            array_push($peilv, $typesssRes[3]['peilv']);
            //不是合
            $z = "";
            if ($last<5){
                //小
                $z.="1,";
                array_push($peilv, $typesssRes[0]['peilv']);
            }else {
                $z.="2,";
            }
            $tmp = $first+$second+$last;
            if ($tmp<14){
                if ($tmp%2==0){
                    $z.="3";
                }else {
                    $z.="4";
                }
            }else {
                if ($tmp%2==0){
                    $z.="6";
                }else {
                    $z.="5";
                }
            }
            $where["xiazhu_type"]=["in",$z];
            $res1 = $jc->getJCDetailsAll($qi_id, $where);
            $where["xiazhu_type"]=["in","8"];
            $where["num"] = $last;
            $res2 = $jc->getJCDetailsAll($qi_id, $where);
            $datas = array_merge($res1,$res2);
        }
        $chongjiang = [];
        $user = new User();
        $array_user = [];
        foreach ($datas as $tmp){
            $uinfo = $user->getUserByUserId($tmp['user_id']);
            if ($uinfo){
                $user->updateMoney($tmp['user_id'], $tmp['money']*$tmp['peilv']/100,true);
                $chongjiangTmp['name'] = $uinfo['nickname'];
                $chongjiangTmp['money'] = $tmp['money']*$tmp['peilv']/10000;
                array_push($chongjiang, $chongjiangTmp);
                //推送给个人
                if (!array_search($tmp['user_id'],$array_user)){
                    array_push($array_user, $tmp['user_id']);
                    $znums[0]=$first;
                    $znums[1]=$second;
                    $znums[2]=$last;
                    $zhongjain['num'] = $znums;
                    $d = $jc->getsomebodyDeatil($qi_id, $tmp['user_id']);
                    $zhongjain['result'] = $d['data'];
                    $zhongjain['name'] = $qiname;
                    $socket->sendinfo($zhongjain,$tmp['user_id']);
                }
                
            }
            
        }
        //推送给所有人，中奖信息
        $p = new Person();
        $chongjiang=$p->getRandPerson($chongjiang,$peilv);
        $socket->sendAllInfo($chongjiang);
        $socket->send_admin_res($jc->getJC($qi_id));
        $jc->finish($qi_id);
        
    }
    /**
     * 未中奖的，代理加佣金
     * @param unknown $qi_id
     * @param unknown $str
     */
    function checkStr2($qi_id,$str,$qiname=""){
        $first = intval(str_get_last($str, 3));
        $second = intval(str_get_last($str, 2));
        $last = intval(str_get_last($str, 1));
        $where["qi_id"]=$qi_id;
        $datas = [];
        $socket = new Socket();
        $jc = new Jc();
        if ($last==$second){
            //合
            $where["xiazhu_type"]=["not in","9"];
            $datas = $jc->getJCDetailsAll($qi_id, $where);
        }else {
            //不是合
            $z = "";
            if ($last<5){
                //小
                $z.="1,";
            }else {
                $z.="2,";
            }
            $tmp = $first+$second+$last;
            if ($tmp<14){
                if ($tmp%2==0){
                    $z.="3";
                }else {
                    $z.="4";
                }
            }else {
                if ($tmp%2==0){
                    $z.="6";
                }else {
                    $z.="5";
                }
            }
            $where["xiazhu_type"]=["not in",$z.",8"];
            $res1 = $jc->getJCDetailsAll($qi_id, $where);
            $where["xiazhu_type"]=["in","8"];
            $where["num"] = ["not in","".$last];
            $res2 = $jc->getJCDetailsAll($qi_id, $where);
            $datas = array_merge($res1,$res2);
        }
        $user = new User();
        $array_user = [];
        foreach ($datas as $tmp){
            $dailiarr = $user->getshangji($tmp['user_id']);
            foreach ($dailiarr as $dailiarrTmp){
                $dailiarrTmp['qi_id'] = $qi_id;
                $dailiarrTmp['money'] = $tmp['money']*$dailiarrTmp['baifenbi']/100;
                $user->addYongjin($dailiarrTmp);
            }
            //推送给个人
            if (!array_search($tmp['user_id'],$array_user)){
                array_push($array_user, $tmp['user_id']);
                $znums[0]=$first;
                $znums[1]=$second;
                $znums[2]=$last;
                $zhongjain['num'] = $znums;

                $d = $jc->getsomebodyDeatil($qi_id, $tmp['user_id']);
                $zhongjain['result'] = $d['data'];
                $zhongjain['name'] = $qiname;
                
                if ($d['count']==0){
                    $socket->sendinfo2($zhongjain,$tmp['user_id']);
                }
                
            }
        }
    
    
    
    }
    
    function getLock()
    {
        $file = "jcinfo.php";
        $data = json_decode(file_get_contents($file), true);
    
        $data['times'] = $this->getTime($data);
        return $data;
    }
    function setLock($data){
        $file = "jcinfo.php";
        file_put_contents($file, json_encode($data));
        
    }
    
    
    
    function setSYSTime($seconds){
        $file = "systime.php";
        $data['systime']=$seconds;
        file_put_contents($file, json_encode($data));
    }
    function getSYSTime(){
        $file = "systime.php";
        $data = json_decode(file_get_contents($file), true);
        return $data['systime'];
    }
    
    function getTime($res)
    {
        $time = $res['time'];
        $seconds = $this->getSYSTime();
        $times = ($time + $seconds) - time();
        if ($times<=0){
            $times=0;
        }
        return $times;
    }
    
    function getJc(){
        //当前，历史
        $data['curr'] = $this->getLock();
        $data['his'] = $this->getJcHis();
        return $data;
    }
    function getJcHis(){
        $file = "jchis.php";
        $data = json_decode(file_get_contents($file), true);
        return $data;
    }
    function saveJchis($data){
        $his = $this->getJcHis();
        if (count($his)>=3) {
            array_pop($his);
        }
        array_push($his, $data);
        $his = array_sort($his, "id");
        $file = "jchis.php";
        file_put_contents($file, json_encode($his));
    }
}
